package logic

import (
	"context"
	"database/sql"
	"encoding/json"
	"share/common"
	"share/models"
	"time"

	"share/internal/svc"
	"share/pb/share"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateShareLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateShareLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateShareLogic {
	return &CreateShareLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// CreateShare 创建分享
func (l *CreateShareLogic) CreateShare(in *share.ShareInfo) (*share.Empty, error) {
	newShare := &models.ShareAggregation{
		UserId: in.UserId, ShareType: in.ShareType, Permission: in.Permission, ExpireType: in.ExpireType,
		ExpireTime: sql.NullTime{Valid: true}, Status: in.Status, FileIDs: in.FileIds, FolderIDs: in.FolderIds,
	}
	if in.ExpireTime != 0 {
		newShare.ExpireTime = sql.NullTime{Valid: true, Time: time.Unix(in.ExpireTime, 0)}
	}
	if in.ShareCode != "" {
		newShare.ShareCode = in.ShareCode
	}
	data, err := json.Marshal(newShare)
	if err != nil {
		return nil, err
	}
	shareLink, err := common.GenerateShareLink(data)
	if err != nil {
		return nil, err
	}
	newShare.ShareLink = shareLink
	err = l.svcCtx.ShareAggregationModel.CreateShare(l.ctx, newShare)
	if err != nil {
		return nil, err
	}
	return &share.Empty{}, nil
}
